<template>
  <el-dialog
    :title="'操作类型管理' + (configData.afterTitle || '')"
    v-model="configData.open"
    width="600px"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    @close="handleClose"
    class="edit-data-dialog"
  >
    <div class="dialog-container">
      <el-form
        :model="dataContainer.form"
        ref="FormElRef"
        :rules="dataContainer.rules"
        label-width="100px"
      >
        <el-form-item label="操作类型名称" prop="name">
          <el-input
            v-model="dataContainer.form.name"
            placeholder="请输入操作类型名称"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="dataContainer.form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入操作类型描述"
          />
        </el-form-item>

        <el-form-item label="状态" prop="isActive" v-if="!configData.isAdd">
          <el-switch
            v-model="dataContainer.form.isActive"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>

        <el-form-item
          label="创建时间"
          prop="createdAt"
          v-if="dataContainer.form.createdAt && !configData.isAdd"
        >
          <el-input v-model="formattedCreatedAt" disabled />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="
            () => {
              dataContainer.closeType = 'cancel';
              configData.open = false;
            }
          "
        >
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
/**
 * 操作类型编辑对话框
 */
import { defineComponent, ref, reactive, nextTick, computed } from "vue";
import { messageError, messageSuccess } from "@/action/MessagePrompt.js";
import operationTypesApi from "@/http/operationTypes.js";

export default defineComponent({
  name: "EditOperationTypeDialog",
  setup() {
    const configData = reactive({
      open: false,
      afterTitle: "",
      isAdd: false
    });

    const FormElRef = ref(null);

    const dataContainer = reactive({
      loading: false,
      closeType: "close",
      resolve: undefined,
      reject: undefined,
      form: {
        name: "",
        description: "",
        isActive: true
      },
      rules: {
        name: [
          { required: true, message: "请输入操作类型名称", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
        ],
        description: [
          { max: 200, message: "描述长度不能超过 200 个字符", trigger: "blur" }
        ],
      },
    });

    // 格式化创建时间
    const formattedCreatedAt = computed(() => {
      if (!dataContainer.form.createdAt) return "";
      return new Date(dataContainer.form.createdAt).toLocaleString();
    });

    // 对话框关闭时的回调
    function handleClose() {
      if (dataContainer.closeType === "confirm") {
        dataContainer.resolve();
      } else {
        dataContainer.reject();
      }
    }

    // 提交表单
    function handleSubmit() {
      FormElRef.value.validate((valid) => {
        if (!valid) return;

        dataContainer.loading = true;

        // 准备提交数据
        const submitData = {
          name: dataContainer.form.name,
          description: dataContainer.form.description,
          isActive: dataContainer.form.isActive
        };

        if (configData.isAdd) {
          // 创建操作类型
          operationTypesApi.createOperationType(submitData)
            .then((res) => {
              messageSuccess("操作类型创建成功");
              dataContainer.closeType = "confirm";
              configData.open = false;
            })
            .catch((err) => {
              console.error("创建操作类型失败", err);
              messageError(err.message || "创建操作类型失败");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        } else {
          // 更新操作类型
          const operationTypeId = dataContainer.form.id;
          if (!operationTypeId) {
            messageError("无法获取操作类型ID");
            dataContainer.loading = false;
            return;
          }

          operationTypesApi.updateOperationType(operationTypeId, submitData)
            .then((res) => {
              messageSuccess("操作类型更新成功");
              dataContainer.closeType = "confirm";
              configData.open = false;
            })
            .catch((err) => {
              console.error("更新操作类型失败", err);
              messageError(err.message || "更新操作类型失败");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        }
      });
    }

    // 初始化对话框数据
    function initData(show = true, data = {}, option = {}) {
      dataContainer.closeType = "close";
      dataContainer.loading = false;

      if (option) {
        if (option.afterTitle !== undefined) {
          configData.afterTitle = option.afterTitle;
        }
        if (option.isAdd !== undefined) {
          configData.isAdd = option.isAdd;
        }
      }

      configData.open = show;

      return new Promise((resolve, reject) => {
        dataContainer.resolve = resolve;
        dataContainer.reject = reject;

        nextTick(() => {
          // 初始化表单数据
          dataContainer.form = {
            name: data.name || "",
            description: data.description || "",
            isActive: data.isActive !== undefined ? data.isActive : true,
            id: data.id || null,
            createdAt: data.createdAt || null
          };
        });
      });
    }

    return {
      configData,
      dataContainer,
      FormElRef,
      formattedCreatedAt,
      handleClose,
      handleSubmit,
      initData,
    };
  },
});
</script>

<style lang="scss" scoped>
.edit-data-dialog {
  .dialog-container {
    padding: 15px;
    box-sizing: border-box;
  }

  .dialog-footer {
    button {
      padding: 8px 20px;
    }
    > *:not(:last-child) {
      margin-right: 10px;
    }
  }
}
</style> 